package leetcode100;

public class lc055 {

    public ListNode sortList(ListNode head) {
        if (head==null || head.next==null) {
            return head;
        }


        ListNode mid = this.findMid(head);
        ListNode rightHead = mid.next;
        mid.next=null;
        ListNode left = sortList(head);
        ListNode right = sortList(rightHead);

        return this.merge(left,right);
    }

    private ListNode merge(ListNode left, ListNode right) {
        ListNode initNode = new ListNode(0);
        ListNode cur= initNode;
        while(left!=null&&right!=null) {
            if (left.val<=right.val) {
                cur.next = left;
                left = left.next;
            } else {
                cur.next = right;
                right = right.next;
            }
            cur=cur.next;
        }
        cur.next = left==null? right:left;

        return initNode.next;
    }

    public ListNode findMid(ListNode head) {
        ListNode slow = head;
        ListNode fast = head.next;

        while( fast != null && fast.next!=null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }

}
